import Axios from "axios";
import resolve from "resolve";

// Axios.defaults.baseURL = 'https://api.example.com';
// Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Axios.defaults.timeout = 6000;

// 添加请求拦截器
Axios.interceptors.request.use(function (config) {
    return config;
}, function (error) {
return Promise.reject(error);
});
// 添加响应拦截器
Axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});
function getParams(data,flg){
    let str="";
    for(let i in data){
        if(str)str+="&";
        str+=`${i}=${encodeURIComponent(data[i])}`
    }
    return !str?"":`${flg?"":"?"}${str}`
}
const COMM_ERROR={reason:"网络异常",error_code:"99999"}
function get(url,data=""){
    return new Promise((resolve,reject)=>{
                Axios.get(`${url}${getParams(data)}`).then(res=>{
                    if(res.status==200&&res.statusText=="OK"){
                        resolve(res.data);
                    }else{
                        reject(COMM_ERROR)
                    }
                })
            })
}
function post(url,data={}){
    return new Promise((resolve,reject)=>{
        Axios.post(url,getParams(data,true)).then(res=>{
            if(res.status==200&&res.statusText=="OK"){
                resolve(res.data);
            }else{
                reject(COMM_ERROR)
            }
        })
    })
}
export {
    get,
    post
}

